package main

import (
	"context"
	"log"
	"net"

	"fmt"

	grpc "google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

type server struct{}

func (s *server) SayHello(ctx context.Context, in *HelloRequest) (*HelloReply, error){
	_msg := "service Recieve:" + in.GetName()
	return &HelloReply{
		Message: &_msg,
	}, nil
}

// 拦截器，简单打印下日志
func LogUnaryInterceptorMiddleware() grpc.UnaryServerInterceptor {
    return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (r interface{}, err error) {
        r, err = handler(ctx, req)

        fmt.Printf("fullMethod(%s), errCode(%v)\n", info.FullMethod, err)
        return r, err
    }
}
func main() {
	lis, err := net.Listen("tcp", ":50000")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }

    // 拦截器
    options := grpc.UnaryInterceptor(LogUnaryInterceptorMiddleware())
    s := grpc.NewServer(options)

    // 注册服务器实现
    RegisterGreeterServer(s, &server{})

    // 注册服务端反射
    reflection.Register(s)

    // 启动服务器
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}
